package com.qysoft.rapid.core;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Logger;
import com.qysoft.rapid.consts.RapidConsts;
import com.qysoft.rapid.exceptions.BizException;
import com.qysoft.rapid.exceptions.RapidException;
import com.qysoft.rapid.plugin.mybatis.MyBatisSessionManager;

/**
 * 平台数据库连接介入，用于事务控制
 * @author liugong
 *
 */
public class RapidDbConnTx implements Interceptor {
	
	private final Logger log = Logger.getLogger(RapidDbConnTx.class);
	
	public void intercept(Invocation ai) {
		interceptForMyBatis(ai);
	}
	
	
	/**
	 * 实现mybatis下的事务控制
	 * @param ai
	 */
	private void interceptForMyBatis(Invocation ai){
		MyBatisSessionManager.setSession(false); 
		doLog("RapidDbConnTx：已获取数据库连接...");
		doLog("RapidDbConnTx：事务已开启...");
		try {
			doLog("RapidDbConnTx：准备执行业务...");
			ai.invoke();
			doLog("RapidDbConnTx：业务已执行...");
			MyBatisSessionManager.commit();
			doLog("RapidDbConnTx：事务已提交...");
		}catch (BizException e){
			MyBatisSessionManager.rollback();
			doLog("RapidDbConnTx：事务已回滚...");
			doLog("BizException："+e.getMessage());
			throw e;
		}catch (Exception e) {
			MyBatisSessionManager.rollback();
			doLog("RapidDbConnTx：事务已回滚...");
			e.printStackTrace();
			throw new RapidException(e.getMessage());
		}finally{
			MyBatisSessionManager.closeSession();
			doLog("RapidDbConnTx：数据库 连接已释放...");
		}
	}
	
	private void doLog(String message){
		if (RapidConsts.isIS_DEV_MODE()) {
			log.warn(message);
		}
	}	
	
}

